/**
 * Theme: Ubold Admin Template
 * Author: Coderthemes
 * Module/App: Main Js
 */

jQuery(document).ready(function($) {
    if ($().datepicker) {
        $('.datepicker-date').datepicker({
            format: "yyyy-mm-dd",
            autoclose: true,
            todayHighlight: true
        });
    }
    if ($().timepicker) {
        $(".datepicker-time").timepicker({
            format: 'yyyy-mm-dd hh:ii:ss',
            autoclose: true,
            todayHighlight: true
        });
    }

    if ($().selectpicker) {
        $('.selectpicker').selectpicker({
            noneSelectedText: ' - ',
        });
        function assign_selectpicker() {
            $.each($('.selectpicker'), function(i,o) {
                $(this).selectpicker('val', $(this).attr('data-value'));
            });
        }
        $('.selectpicker').on('loaded.bs.select', function(ev){
            assign_selectpicker();
        });
        assign_selectpicker();
    }

    if ($().summernote) {

        $.each($('.summernote'), function(i,o) {

            var $summernote = $(o);

            $summernote.summernote({
                height: 270,
                width: '100%',
                airMode: false,
                minHeight: 300,             // set minimum height of editor
                callbacks: {
                    onInit: function(contents, $editable) {
                        $summernote.closest('.form-group').find('input#' + $summernote.attr('data-submitto')).val($summernote.summernote('code'));
                    },
                    onChange: function(contents, $editable) {
                        $summernote.closest('.form-group').find('input#' + $summernote.attr('data-submitto')).val(contents);
                    },
                    onImageUpload: function(files) {
                        // upload image to server and create imgNode...
                        console.log(files);
                        formData = new FormData();
                        formData.append('image', files[0], "summernote.png");
                        $.ajax({
                            url: $summernote.attr('data-upload'),
                            type: "POST",
                            data: formData,
                            processData: false,  // 告诉jQuery不要去处理发送的数据
                            contentType: false,   // 告诉jQuery不要去设置Content-Type请求头
                            dataType : "json",
                            success: function(o) {
                                console.log(o);
                                if (o.code == 0) {
                                    $summernote.summernote('insertImage', '/' + o.data[0]);
                                } else {
                                    show_error(o.error);
                                }
                            }

                        });

                    }
                }
            });
        });



        if (Dropzone) {
            Dropzone.autoDiscover = false;

            $.each($('.summer_dropzone'), function(i,o) {

                var myDropzone = new Dropzone("div#" + $(o).attr('id'), { dictDefaultMessage: '<h4>拖入文件或图片</h4><h5>可一个或多个</h5>', url: $(o).attr('data-upload')});

                myDropzone.on("complete", function(file) {
                    setTimeout(function(){
                        myDropzone.removeFile(file);
                    }, 1000);
                    console.log(file);
                    var response = file.xhr.response;
                    response = JSON.parse(response);
                    $summer = $(o).closest('.form-group').find('.summernote');
                    if (response.code == 0) {
                        if (file.type.match(/image\//)) {
                            $summer.summernote('insertImage', '/Public/' + response.data[0]);
                        } else {
                            var $nodes = $('<p><strong>附件下载：</strong><a href="/#url">#filename</a> </p>'.replace('#url', response.data[0]).replace('#filename', file.name));
                            $.each($nodes, function(i,o){
                                console.log($(o)[0]);
                                $summer.summernote('insertNode', $(o)[0]);
                            });
                        }

                    } else {
                        show_error(response.error);
                    }

                });
            });

            $.each($('.filename_dropzone'), function(i,o) {

                var myDropzone = new Dropzone("div#" + $(o).attr('id'), { dictDefaultMessage: '', url: $(o).attr('data-upload')});

                myDropzone.on("complete", function(file) {
                    // setTimeout(function(){
                    //   myDropzone.removeFile(file);
                    // }, 1000);
                    console.log(file);
                    var response = file.xhr.response;
                    response = JSON.parse(response);
                    if (response.code == 0) {
                        show_error('上传成功');
                    } else {
                        show_error(response.error);
                    }
                });
            });



        }

    }


});


!function($) {
    "use strict";

    var Sidemenu = function() {
        this.$body = $("body"),
            this.$openLeftBtn = $(".open-left"),
            this.$menuItem = $("#sidebar-menu a")
    };
    Sidemenu.prototype.openLeftBar = function() {
        $("#wrapper").toggleClass("enlarged");
        $("#wrapper").addClass("forced");

        if($("#wrapper").hasClass("enlarged") && $("body").hasClass("fixed-left")) {
            $("body").removeClass("fixed-left").addClass("fixed-left-void");
        } else if(!$("#wrapper").hasClass("enlarged") && $("body").hasClass("fixed-left-void")) {
            $("body").removeClass("fixed-left-void").addClass("fixed-left");
        }

        if($("#wrapper").hasClass("enlarged")) {
            $(".left ul").removeAttr("style");
        } else {
            $(".subdrop").siblings("ul:first").show();
        }

        toggle_slimscroll(".slimscrollleft");
        $("body").trigger("resize");
    },
        //menu item click
        Sidemenu.prototype.menuItemClick = function(e) {
            if(!$("#wrapper").hasClass("enlarged")){
                if($(this).parent().hasClass("has_sub")) {
                    e.preventDefault();
                }
                if(!$(this).hasClass("subdrop")) {
                    // hide any open menus and remove all other classes
                    $("ul",$(this).parents("ul:first")).slideUp(350);
                    $("a",$(this).parents("ul:first")).removeClass("subdrop");
                    $("#sidebar-menu .pull-right i").removeClass("md-remove").addClass("md-add");

                    // open our new menu and add the open class
                    $(this).next("ul").slideDown(350);
                    $(this).addClass("subdrop");
                    $(".pull-right i",$(this).parents(".has_sub:last")).removeClass("md-add").addClass("md-remove");
                    $(".pull-right i",$(this).siblings("ul")).removeClass("md-remove").addClass("md-add");
                }else if($(this).hasClass("subdrop")) {
                    $(this).removeClass("subdrop");
                    $(this).next("ul").slideUp(350);
                    $(".pull-right i",$(this).parent()).removeClass("md-remove").addClass("md-add");
                }
            }
        },

        //init sidemenu
        Sidemenu.prototype.init = function() {
            var $this  = this;
            //bind on click
            $(".open-left").click(function(e) {
                e.stopPropagation();
                $this.openLeftBar();
            });

            // LEFT SIDE MAIN NAVIGATION
            $this.$menuItem.on('click', $this.menuItemClick);

            // NAVIGATION HIGHLIGHT & OPEN PARENT
            $("#sidebar-menu ul li.has_sub a.active").parents("li:last").children("a:first").addClass("active").trigger("click");
        },

        //init Sidemenu
        $.Sidemenu = new Sidemenu, $.Sidemenu.Constructor = Sidemenu

}(window.jQuery),


    function($) {
        "use strict";

        var FullScreen = function() {
            this.$body = $("body"),
                this.$fullscreenBtn = $("#btn-fullscreen")
        };

        //turn on full screen
        // Thanks to http://davidwalsh.name/fullscreen
        FullScreen.prototype.launchFullscreen  = function(element) {
            if(element.requestFullscreen) {
                element.requestFullscreen();
            } else if(element.mozRequestFullScreen) {
                element.mozRequestFullScreen();
            } else if(element.webkitRequestFullscreen) {
                element.webkitRequestFullscreen();
            } else if(element.msRequestFullscreen) {
                element.msRequestFullscreen();
            }
        },
            FullScreen.prototype.exitFullscreen = function() {
                if(document.exitFullscreen) {
                    document.exitFullscreen();
                } else if(document.mozCancelFullScreen) {
                    document.mozCancelFullScreen();
                } else if(document.webkitExitFullscreen) {
                    document.webkitExitFullscreen();
                }
            },
            //toggle screen
            FullScreen.prototype.toggle_fullscreen  = function() {
                var $this = this;
                var fullscreenEnabled = document.fullscreenEnabled || document.mozFullScreenEnabled || document.webkitFullscreenEnabled;
                if(fullscreenEnabled) {
                    if(!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement) {
                        $this.launchFullscreen(document.documentElement);
                    } else{
                        $this.exitFullscreen();
                    }
                }
            },
            //init sidemenu
            FullScreen.prototype.init = function() {
                var $this  = this;
                //bind
                $this.$fullscreenBtn.on('click', function() {
                    $this.toggle_fullscreen();
                });
            },
            //init FullScreen
            $.FullScreen = new FullScreen, $.FullScreen.Constructor = FullScreen

    }(window.jQuery),



//main app module
    function($) {
        "use strict";

        var App = function() {
            this.VERSION = "1.1.0",
                this.AUTHOR = "Coderthemes",
                this.SUPPORT = "coderthemes@gmail.com",
                this.pageScrollElement = "html, body",
                this.$body = $("body")
        };

        //on doc load
        App.prototype.onDocReady = function(e) {
            FastClick.attach(document.body);
            resizefunc.push("initscrolls");
            resizefunc.push("changeptype");

            $('.animate-number').each(function(){
                $(this).animateNumbers($(this).attr("data-value"), true, parseInt($(this).attr("data-duration")));
            });

            //RUN RESIZE ITEMS
            $(window).resize(debounce(resizeitems,100));
            $("body").trigger("resize");

            // right side-bar toggle
            $('.right-bar-toggle').on('click', function(e){
                e.preventDefault();
                $('#wrapper').toggleClass('right-bar-enabled');
            });


        },
            //initilizing
            App.prototype.init = function() {
                var $this = this;
                //document load initialization
                $(document).ready($this.onDocReady);
                //init side bar - left
                $.Sidemenu.init();
                //init fullscreen
                $.FullScreen.init();
            },

            $.App = new App, $.App.Constructor = App

    }(window.jQuery),

//initializing main application module
    function($) {
        "use strict";
        $.App.init();
    }(window.jQuery);



/* ------------ some utility functions ----------------------- */
//this full screen
var toggle_fullscreen = function () {

}

function executeFunctionByName(functionName, context /*, args */) {
    var args = [].slice.call(arguments).splice(2);
    var namespaces = functionName.split(".");
    var func = namespaces.pop();
    for(var i = 0; i < namespaces.length; i++) {
        context = context[namespaces[i]];
    }
    return context[func].apply(this, args);
}
var w,h,dw,dh;
var changeptype = function(){
    w = $(window).width();
    h = $(window).height();
    dw = $(document).width();
    dh = $(document).height();

    if(jQuery.browser.mobile === true){
        $("body").addClass("mobile").removeClass("fixed-left");
    }

    if(!$("#wrapper").hasClass("forced")){
        if(w > 990){
            $("body").removeClass("smallscreen").addClass("widescreen");
            $("#wrapper").removeClass("enlarged");
        }else{
            $("body").removeClass("widescreen").addClass("smallscreen");
            $("#wrapper").addClass("enlarged");
            $(".left ul").removeAttr("style");
        }
        if($("#wrapper").hasClass("enlarged") && $("body").hasClass("fixed-left")){
            $("body").removeClass("fixed-left").addClass("fixed-left-void");
        }else if(!$("#wrapper").hasClass("enlarged") && $("body").hasClass("fixed-left-void")){
            $("body").removeClass("fixed-left-void").addClass("fixed-left");
        }

    }
    toggle_slimscroll(".slimscrollleft");
}


var debounce = function(func, wait, immediate) {
    var timeout, result;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) result = func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) result = func.apply(context, args);
        return result;
    };
}

function resizeitems(){
    if($.isArray(resizefunc)){
        for (i = 0; i < resizefunc.length; i++) {
            window[resizefunc[i]]();
        }
    }
}

function initscrolls(){
    if(jQuery.browser.mobile !== true){
        //SLIM SCROLL
        $('.slimscroller').slimscroll({
            height: 'auto',
            size: "5px"
        });

        $('.slimscrollleft').slimScroll({
            height: 'auto',
            position: 'right',
            size: "5px",
            color: '#dcdcdc',
            wheelStep: 5
        });
    }
}
function toggle_slimscroll(item){
    if($("#wrapper").hasClass("enlarged")){
        $(item).css("overflow","inherit").parent().css("overflow","inherit");
        $(item). siblings(".slimScrollBar").css("visibility","hidden");
    }else{
        $(item).css("overflow","hidden").parent().css("overflow","hidden");
        $(item). siblings(".slimScrollBar").css("visibility","visible");
    }
}

var wow = new WOW(
    {
        boxClass: 'wow', // animated element css class (default is wow)
        animateClass: 'animated', // animation css class (default is animated)
        offset: 50, // distance to the element when triggering the animation (default is 0)
        mobile: false        // trigger animations on mobile devices (true is default)
    }
);
wow.init();
